import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const superAdmin = '超级管理员'

const getDefaultState = () => {
  return {
    adminToken:'',
    adminName:'',
    token: getToken(),
    name: '',
    role: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ADMIN_TOKEN: (state, token) => {
    state.adminToken = token
  },
  SET_ADMIN_NAME: (state, name) => {
    state.adminName = name
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLE: (state, role) => {
    state.role = role
  }
}

const actions = {
  // test mapActions
  setRoleAsync({ commit },role){
    setTimeout(()=>{
      commit('SET_ROLE',role)
    },2000)
  },
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve,reject) => {
      commit('SET_TOKEN', 'token')
      commit('SET_NAME', 'mf')
      commit('SET_ROLE', 'admin')
      setToken('token')
      resolve()
      return
     login(userInfo).then(res=>{
       const {token,username,role } = res
       if(role === superAdmin){
         commit('SET_ADMIN_TOKEN', token)
         commit('SET_ADMIN_NAME', username)
       }
       setToken(token)
       commit('SET_TOKEN', token)
       commit('SET_NAME', username)
       commit('SET_ROLE', role)
       resolve()
     }).catch(()=>{
       reject()
     })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_NAME', 'mf')
      commit('SET_ROLE', 'admin')
      resolve()
      return
      getInfo().then(res=>{
        commit('SET_NAME', res.username)
        commit('SET_ROLE', res.role)
        resolve()
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      const {role, adminToken, adminName } = state
      // 如果是子账户，退出时判断，如果时通过超级管理员登录的，退出到超级管理员管理后台
      if(role !== superAdmin && adminToken && adminName){
        console.log('退出到超级管理员')
        setToken(adminToken)
        commit('SET_TOKEN', adminToken)
        commit('SET_NAME', adminName)
        commit('SET_ROLE', superAdmin)
        return
      }
      // 正常退出
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
